//
//  NearFoodViewController.m
//  Food & Delights
//
//  Created by dlios on 15-7-13.
//  Copyright (c) 2015年 李志远. All rights reserved.
//

#import "NearFoodViewController.h"
#import "NearFoodModel.h"
#import "NearFoodTableViewCell.h"
#import "NearFoodDetailsViewController.h"
#import "MJRefresh.h"
@interface NearFoodViewController ()<UITableViewDataSource,UITableViewDelegate>
@property (nonatomic, retain) UITableView *myTableView;
@property (nonatomic, retain) NSMutableArray *tableArr;
@property (nonatomic, assign) float locationLat;
@property (nonatomic, assign) float locationLng;
@property (nonatomic, retain) NSMutableArray *footArr;
@property (nonatomic, assign) NSInteger page;
@property (nonatomic, retain) NSString *url;
@property (nonatomic, retain) MBProgressHUD *progress;

@end


@implementation NearFoodViewController

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.tableArr = [NSMutableArray array];
        self.footArr = [NSMutableArray array];
    }
    
    return self;
}

- (void)dealloc
{

}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self.navigationItem setLeftBarButtonItem:nil animated:NO];
self.title = @"附近美食";
    [self startLocation];
    [self createTableView];
    [self setupRefresh];
    Reachability *r = [Reachability reachabilityWithHostName:@"www.baidu.com"];
    if (r.currentReachabilityStatus == NotReachable) {
        UIAlertView *alert1 = [[UIAlertView alloc] initWithTitle:@"提示" message:@"网络连接失败" delegate:self cancelButtonTitle:@"好" otherButtonTitles:nil];
        [alert1 show];
    }else{
        [self createProgress];
    }
}

- (void)createProgress
{
    self.progress = [[MBProgressHUD alloc] initWithView:self.view];
    [self.progress show:YES];
    self.progress.labelText = @"稍等";
    self.progress.detailsLabelText = @"正在加载...";
    [self.view addSubview:self.progress];
    
}


- (void)setupRefresh
{
    // 下拉刷新
    [self.myTableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    // 上拉加载
    [self.myTableView addFooterWithTarget:self action:@selector(footerRereshing)];
    // 一进程序自动刷新
    [self.myTableView headerBeginRefreshing];
    
    // 设置文字(也可以不设置,默认的文字在MJRefreshConst中修改)
    self.myTableView.headerPullToRefreshText = @"下拉可以刷新了";
    self.myTableView.headerReleaseToRefreshText = @"松开马上刷新了";
    self.myTableView.headerRefreshingText = @"正在帮你刷新中,不客气";
    
    self.myTableView.footerPullToRefreshText = @"上拉可以加载更多数据了";
    self.myTableView.footerReleaseToRefreshText = @"松开马上加载更多数据了";
    self.myTableView.footerRefreshingText = @"正在帮你加载中,不客气";
    
}

- (void)headerRereshing
{
    NSString *str1 = @"http://api.meishixing.com/search/nearby/recommandplace/";
    NSString *str2 = [NSString stringWithFormat:@"lng=%f&lat=%f",self.locationLng,self.locationLat];
    NSString *str3 = @"&page=1&session_id=000012b2aeca4600ed78e8f04006451605e8cc&distance=3000&food_category_name=&price=";
    self.url = [NSString stringWithFormat:@"%@%@%@",str1,str2,str3];
    [self.footArr removeAllObjects];
    [AFNet connectNetGetDataWithURLString:self.url parameters:nil finishblock:^(id result) {
       
        NSMutableArray *arr = [result objectForKey:@"result"];
        for (NSDictionary *dic in arr) {
            NearFoodModel *model = [[NearFoodModel alloc] initWithDic:dic];
            [self.footArr addObject:model];
           
        }
        [self.tableArr removeAllObjects];
        [self.tableArr addObjectsFromArray:self.footArr];
        [self.myTableView reloadData];
    }];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        [self.myTableView reloadData];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.myTableView headerEndRefreshing];
    });
    self.page = 2;
}

- (void)footerRereshing
{
   
    NSString *str1 = @"http://api.meishixing.com/search/nearby/recommandplace/";
    NSString *str2 = [NSString stringWithFormat:@"lng=%f&lat=%f",self.locationLng,self.locationLat];
    NSString *str3 = [NSString stringWithFormat:@"&page=%ld",self.page ++];
    NSString *str4 = @"&session_id=000012b2aeca4600ed78e8f04006451605e8cc&distance=3000&food_category_name=&price=";
    NSString *url = [NSString stringWithFormat:@"%@%@%@%@",str1,str2,str3,str4];
    
    [self.footArr removeAllObjects];
    [AFNet connectNetGetDataWithURLString:url parameters:nil finishblock:^(id result) {
        
        NSMutableArray *arr = [result objectForKey:@"result"];
        for (NSDictionary *dic in arr) {
            NearFoodModel *model = [[NearFoodModel alloc] initWithDic:dic];
            [self.footArr addObject:model];
           
        }
        [self.tableArr addObjectsFromArray:self.footArr];
        [self.myTableView reloadData];
    }];

    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        [self.myTableView reloadData];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.myTableView footerEndRefreshing];
    });

}

- (void)startLocation
{
    self.locationManager = [[CLLocationManager alloc] init];
    // 设置定位精度
    
    if (![CLLocationManager locationServicesEnabled] || [CLLocationManager authorizationStatus] != kCLAuthorizationStatusAuthorizedWhenInUse) {
        
        [_locationManager requestWhenInUseAuthorization];
    }
    [self.locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
    self.locationManager.delegate = self;
    CLLocationDistance distance=10.0;
    self.locationManager.distanceFilter = distance;
    // 开始定位
    [self.locationManager startUpdatingLocation];
    //[_locationManager release];
}


- (void)getData
{
    NSString *str1 = @"http://api.meishixing.com/search/nearby/recommandplace/";
    NSString *str2 = [NSString stringWithFormat:@"lng=%f&lat=%f",self.locationLng,self.locationLat];
    NSString *str3 = @"&page=1&session_id=000012b2aeca4600ed78e8f04006451605e8cc&distance=3000&food_category_name=&price=";
    self.url = [NSString stringWithFormat:@"%@%@%@",str1,str2,str3];
    
    [AFNet connectNetGetDataWithURLString:self.url parameters:nil finishblock:^(id result) {
        [self.progress hide:YES];
        NSMutableArray *arr = [result objectForKey:@"result"];
        for (NSDictionary *dic in arr) {
            NearFoodModel *model = [[NearFoodModel alloc] initWithDic:dic];
            [self.footArr addObject:model];
           
        }
        [self.tableArr addObjectsFromArray:self.footArr];
        [self.myTableView reloadData];
    }];
    
}

#pragma mark= 定位

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    CLLocation *location = [locations firstObject];
    CLLocationCoordinate2D coordinate = location.coordinate;
    self.locationLat = coordinate.latitude;
    self.locationLng = coordinate.longitude;
    [self getData];
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    NSLog(@"定位失败:%@",error);
    
}

- (void)createTableView
{
    self.myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64-49) style:UITableViewStylePlain];
    self.myTableView.dataSource = self;
    self.myTableView.delegate = self;
    [self.myTableView registerClass:[NearFoodTableViewCell class] forCellReuseIdentifier:@"cell"];
    [self.view addSubview:self.myTableView];
    //[_myTableView release];
    
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.tableArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NearFoodTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    NearFoodModel *model = self.tableArr[indexPath.row];
    cell.model = model;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NearFoodModel *model = self.tableArr[indexPath.row];
    NearFoodDetailsViewController *detailsVC = [[NearFoodDetailsViewController alloc] init];
    detailsVC.url = model.place_ID;
    [self.navigationController pushViewController:detailsVC animated:YES];
    
}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
